﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrawlerCore;
using WCrawlerLib;
using WCrawlerLib.WebSession;
using WCrawlerLib.WebSession.vBulletin;
using WCrawlerLib.WebSession.IPBoard;
using WCrawlerLib.WebSession.phpBB;

using System.Threading;
using System.Threading.Tasks;

namespace WCrawler
{
    public partial class frmPostThread : System.Web.UI.Page
    {
        /// <summary>
        /// Biến dùng cho thể hiện số thứ tự của một forum
        /// </summary>
        private int _index = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            //enable javascript
            //this.Page.Header.DataBind();

            if (!Page.IsPostBack)
            {
                GroupDropDownList.Items.Insert(0, new ListItem());
                GroupDropDownList.DataBind();

                dropDownListStatus.SelectedIndex = 1;

                btnPostReply.Enabled = false;
                btnPostUpdate.Enabled = false;

                gridViewForumThreads.Visible = false;
                gridViewForums.Visible = false;
            }
        }

        protected void GroupDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            dropDownListStatus_SelectedIndexChanged(null, null);
        }

        protected void ForumLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            GridView gridViewPosts = ucPost.GetGridViewControl();
            if (gridViewPosts.SelectedDataKey != null)
            {
                Forum obj = new Forum();
                var forumsQuery = obj.GetPostedForums((int)gridViewPosts.SelectedDataKey["PostId"], dropDownListStatus.SelectedIndex)
                                     .WhereGroup(GroupDropDownList.SelectedValue)
                                     .IsApproved(true);
                e.Result = forumsQuery;
                //e.Result = SearchQuery();
            }
            else
                e.Result = null;
        }


        public void ucGridViewPosts_SelectedIndexChanged(object sender, EventArgs e)
        {
            dropDownListStatus.SelectedIndex = 1;
            dropDownListStatus_SelectedIndexChanged(null, null);
        }

        protected void dropDownListStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListStatus.SelectedIndex == 1) //have been posted already
            {
                btnPostReply.Enabled = true;
                btnPostUpdate.Enabled = true;

                gridViewForumThreads.Visible = true;
                gridViewForums.Visible = false;
                gridViewForumThreads.DataBind();
                
            }
            else //Haven't been post yet or all forums
            {
                gridViewForumThreads.Visible = false;
                gridViewForums.Visible = true;
                gridViewForums.DataBind();
                
                btnPostReply.Enabled = false;
                btnPostUpdate.Enabled = false;
            }
        }

        //protected void PostForumDetailsLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        //{
        //    if (gridViewPosts.SelectedDataKey != null)
        //        e.Result = ViewPosts();
        //}

        /// <summary>
        /// Check validation
        /// </summary>
        /// <returns></returns>
        public int CheckInfo()
        {
            BrowserSession br = new BrowserSession_EmptyForum();
            if (!br.Authentication())
                return -1;

            GridView gridViewPosts = ucPost.GetGridViewControl();
            if (gridViewPosts.SelectedDataKey["PostId"] == null)
            {
                lblReport.Text = "No post selected";
                return -1;
            }
            int postId = (int)gridViewPosts.SelectedDataKey["PostId"];

            //Check file before post
            FilePost objFilePost = new FilePost();
            objFilePost.CheckFilePostsByPost(postId);

            //check is exist files alive
            if (!objFilePost.CheckFilesAlive(postId))
            {
                lblReport.Text = "All files are dead";
                return -1;
            }
            return postId;
        }

        

        protected void btnDoPost_Click(object sender, EventArgs e)
        {
            int postId = CheckInfo();
            if (postId == -1)
                return;
            if (dropDownListStatus.SelectedIndex != 1)
            {
                Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
                {
                    CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                    if (chkBx != null && chkBx.Checked)
                    {
                        int forumId = (int)gridViewForums.DataKeys[di.RowIndex].Value;
                        Forum objForum = new Forum();
                        objForum.PostNewThread(postId, forumId);


                        ////New Code
                        //Post objPost = new Post();
                        //objPost = objPost.GetPost(postId);
                        //IForumSession objForumSession = GetForumSession(forumId);
                        //objForumSession.PostNewThread(objPost);

                    }
                });
            }
            else //if have posted already then have posted again
            {
                //Post again
                Parallel.ForEach<GridViewRow>(gridViewForumThreads.Rows.OfType<GridViewRow>(), di =>
                {
                    CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                    if (chkBx != null && chkBx.Checked)
                    {
                        int forumThreadId = (int)gridViewForumThreads.DataKeys[di.RowIndex].Value;
                        ForumThread objForumThread = new ForumThread();
                        objForumThread = objForumThread.GetForumThread(forumThreadId);
                        Forum objForum = new Forum();
                        objForum.PostNewThread(postId, objForumThread.Forum.ForumId);
                    }
                });
            }
            gridViewForums.DataBind();
            gridViewForumThreads.DataBind();
        }

        protected void btnPostReply_Click(object sender, EventArgs e)
        {
            int postId = CheckInfo();
            if (postId == -1)
                return;

            Session["IsEdit"] = false;
            mdlPopup.Show();
            
        }

        protected void btnPostUpdate_Click(object sender, EventArgs e)
        {
            int postId = CheckInfo();
            if (postId == -1)
                return;

            Session["IsEdit"] = true;
            mdlPopup.Show();
        }

        protected void btnEditWithoutReply_Click(object sender, EventArgs e)
        {
            int postId = CheckInfo();
            if (postId == -1)
                return;

            Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
            {
                CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                {
                    int forumId = (int)gridViewForums.DataKeys[di.RowIndex].Value;
                    Forum objForum = new Forum();
                    objForum.PostUpdateWithoutReply(forumId, postId);
                }
            });
            gridViewForums.DataBind();
        }

        public void FormatGridView(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
                _index = gridViewForums.PageSize * gridViewForums.PageIndex + 1;
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Create order numbers
                ((Label)e.Row.FindControl("lblNum")).Text = (_index++).ToString();

                GridView gridViewPosts = ucPost.GetGridViewControl();
                string postId = gridViewPosts.SelectedDataKey["PostId"].ToString();

                Forum objForum = new Forum();
                ForumThread objForumThread = new ForumThread();
                
                if (((GridView)sender).ID == gridViewForums.ID)
                {
                    string forumId = gridViewForums.DataKeys[e.Row.RowIndex]["ForumId"].ToString();
                    objForum = objForum.GetForum(int.Parse(forumId));
                    objForumThread = objForumThread.GetForumThread(int.Parse(postId), int.Parse(forumId));
                }
                else
                {
                    objForumThread = objForumThread.GetForumThread((int)gridViewForumThreads.DataKeys[e.Row.RowIndex]["ForumThreadId"]);
                    objForum = objForum.GetForum(objForumThread.ForumId);
                }

                Post objPost = new Post();
                objPost = objPost.GetPost(int.Parse(postId));

                //Check forum topic is exists?
                ForumTopic objForumTopic = new ForumTopic();
                objForumTopic = objForumTopic.GetExactlyPostTopicValue(objForum.ForumId, objPost.TopicId);

                //Check postdetail is exists?
                PostDetail objPostDetail = new PostDetail();
                objPostDetail = objPostDetail.GetExactlyPostDetail(objPost.PostId, objForum.LanguageId);

                if (((GridView)sender).ID == gridViewForums.ID)
                {
                    //======================================================================================
                    //CHECK THE FORUM IS APPROVED?
                    CheckBox chkCheckItem = (CheckBox)e.Row.FindControl("chkCheckItem");
                    if (!objForum.IsApproved)
                    {
                        chkCheckItem.Visible = false;
                        return;
                    }
                    

                    //CHECK THE FORUM CAN POST?
                    if (objForumTopic == null || objPostDetail == null)
                    {
                        chkCheckItem.Visible = false;
                        return;
                    }
                    else
                        chkCheckItem.Visible = true;


                    if (objForumThread != null)
                    {
                        HyperLink hyperLinkThread = (HyperLink)e.Row.FindControl("hyperLinkThread");
                        hyperLinkThread.NavigateUrl = GeneralClass.GetFullUrl(objForum.ForumUrl, objForumThread.ThreadUrl);
                        hyperLinkThread.Text = objForumThread.ThreadNum.ToString();

                        Label lblCreateOn = (Label)e.Row.FindControl("lblCreateOn");
                        lblCreateOn.Text = objForumThread.CreateOn.HasValue ? objForumThread.CreateOn.Value.ToShortDateString() : "";

                        Label lblUpdateOn = (Label)e.Row.FindControl("lblUpdateOn");
                        lblUpdateOn.Text = objForumThread.UpdateOn.HasValue ? objForumThread.UpdateOn.Value.ToShortDateString() : "";
                    }
                    else
                    {
                        //Get new thread url template
                        ForumTemplateDetail objForumTemplateDetail = new ForumTemplateDetail();
                        string newThreadUrl = objForumTemplateDetail.GetNewThreadUrl(objForum.ForumId, objForum.ForumTypeId);
                        string fValue = objForumTopic.fValue.Value.ToString();
                        //Replace pattern to f value
                        newThreadUrl = newThreadUrl.Replace("§", "&sect").Replace("[fid]", fValue);

                        HyperLink hyperLinkThread = (HyperLink)e.Row.FindControl("hyperLinkThread");
                        hyperLinkThread.NavigateUrl = GeneralClass.GetFullUrl(objForum.ForumUrl, newThreadUrl);
                        hyperLinkThread.Text = fValue;
                        hyperLinkThread.Target = "_blank";
                    }
                }
                
                HyperLink hyperLinkTopic = (HyperLink)e.Row.FindControl("hyperLinkTopic");
                if (!string.IsNullOrEmpty(objForumTopic.ForumTopicName))
                {
                    hyperLinkTopic.NavigateUrl = GeneralClass.GetFullUrl(objForum.ForumUrl, objForumTopic.ForumTopicUrl);
                    hyperLinkTopic.Text = objForumTopic.ForumTopicName;
                }
                else
                {
                    hyperLinkTopic.NavigateUrl = objForum.ForumUrl;
                    hyperLinkTopic.Text = string.Format("{0}(f={1})", objForumTopic.Topic.TopicName, objForumTopic.fValue.ToString());
                }
            }
        }

        protected void gridViewForums_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            FormatGridView(sender, e);
        }

        protected void btnUpdateInfo_Click(object sender, EventArgs e)
        {

        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            if (txtReplyContent.Text.Trim() == string.Empty)
            {
                lblMessage.Text = "No message";
                return;
            }
            GridView gridViewPosts = ucPost.GetGridViewControl();
            BrowserSession br = new BrowserSession_EmptyForum();
            if (!br.Authentication())
                return;

            if (gridViewPosts.SelectedDataKey["PostId"] == null)
            {
                lblMessage.Text = "Select a post before send";
                return;
            }

            string replyMessage = txtReplyContent.Text;//"The links are still alive (" + DateTime.Now.ToShortDateString() + ")";

            if ((bool)Session["IsEdit"])
            {
                Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
                {
                    CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                    if (chkBx != null && chkBx.Checked)
                    {
                        int forumId = (int)gridViewForums.DataKeys[di.RowIndex].Value;
                        int postId = (int)gridViewPosts.SelectedDataKey["PostId"];
                        Forum objForum = new Forum();
                        objForum.PostUpdateWithReply(postId, forumId, replyMessage);
                    }
                });
            }
            else
            {
                Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
                {
                    CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                    if (chkBx != null && chkBx.Checked)
                    {
                        int forumId = (int)gridViewForums.DataKeys[di.RowIndex].Value;
                        int postId = (int)gridViewPosts.SelectedDataKey["PostId"];
                        Forum objForum = new Forum();
                        objForum.PostNewReply(postId, forumId, true, replyMessage);
                    }
                });
            }
            
            gridViewForums.DataBind();
        }

        protected void ForumThreadsLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            GridView gridViewPosts = ucPost.GetGridViewControl();
            if (gridViewPosts.SelectedDataKey != null)
            {
                string postId = gridViewPosts.SelectedDataKey["PostId"].ToString();
                ForumThread objForumThread = new ForumThread();
                e.Result = objForumThread.GetForumThreadsByPost(int.Parse(postId), GroupDropDownList.SelectedValue, dropDownListStatus.SelectedIndex);
            }
        }

        protected void gridViewForumThreads_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //FormatGridView(sender, e);
        }

        protected void btnDeleteThreads_Click(object sender, EventArgs e)
        {

        }

        protected void dropDownListNumberOfRows_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListNumberOfRows.SelectedIndex != (dropDownListNumberOfRows.Items.Count - 1))
            {
                if (dropDownListStatus.SelectedIndex == 0)
                {
                    gridViewForums.AllowPaging = true;
                    gridViewForums.PageSize = int.Parse(dropDownListNumberOfRows.SelectedItem.Value);
                }
                else
                {
                    gridViewForumThreads.AllowPaging = true;
                    gridViewForumThreads.PageSize = int.Parse(dropDownListNumberOfRows.SelectedItem.Value);
                }
            }
            else
            {
                gridViewForums.AllowPaging = false;
                gridViewForumThreads.AllowPaging = false;
            }
        }

        protected void btnPostByWebBrowser_Click(object sender, EventArgs e)
        {

        }

        protected void btnOpenNewThreadUrl_Click(object sender, EventArgs e)
        {
            GridView gridViewPosts = ucPost.GetGridViewControl();
            int postId = (int)gridViewPosts.SelectedDataKey["PostId"];
            Post objPost = new Post();
            objPost = objPost.GetPost(postId);

            Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
            {
                CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                {
                    //int forumId = (int)gridViewForums.DataKeys[di.RowIndex].Value;
                    //Forum objForum = new Forum();
                    //objForum = objForum.GetForum(forumId);

                    ////======================================================================================
                    ////Get f value of thread id of a forum
                    //ForumTopic objForumTopic = new ForumTopic();
                    //objForumTopic = objForumTopic.GetExactlyPostTopicValue(objForum.ForumId, objPost.TopicId);

                    ////Get new thread url template
                    //ForumTemplateDetail objForumTemplateDetail = new ForumTemplateDetail();
                    //string newThreadUrl = objForumTemplateDetail.GetNewThreadUrl(objForum.ForumId, objForum.ForumTypeId);

                    ////Replace pattern to f value
                    //newThreadUrl = newThreadUrl.Replace("§", "&sect").Replace("[fid]", objForumTopic.fValue.Value.ToString());
                    //newThreadUrl = GeneralClass.GetFullUrl(objForum.ForumUrl, newThreadUrl);

                    ////Open in new tab
                    ////Response.Redirect(newThreadUrl);
                    //Response.Write(string.Format("<script> window.open('{0}'); </script>",newThreadUrl));
                    //Response.End();

                    HyperLink hyperLinkThread = (HyperLink)di.FindControl("hyperLinkThread");
                    //Response.Redirect(hyperLinkThread.NavigateUrl);

                    Response.Write(string.Format("<script> window.open('{0}',\"\",\"\"); </script>", hyperLinkThread.NavigateUrl));
                    Response.End();
                }
            });
        }

        
    }
}